package com.sgb.kjwl.viewmodel.self.carMakers;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.sgb.kjwl.api.APIManager;
import com.swgk.core.base.api.ICallBack;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.self.CarriageSelectEntity;
import com.sgb.kjwl.model.entity.self.SubSetEntity;
import com.sgb.kjwl.model.entity.self.SubSetListEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.model.entity.transport.SingleItemConstant;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.util.MToast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class SubscriptionSetModel extends AndroidViewModel {
    //第一次设置tag
    private final String TAG_FIRST = "FIRST_SET_TAG";
    //
    public MutableLiveData<SubSetEntity> ldSub = new MutableLiveData<>();
    public MutableLiveData<List<GoodsInfoTypeEntity3>> ldCarType = new MutableLiveData<>();

    public SubscriptionSetModel(@NonNull Application application) {
        super(application);
    }

    //订阅列表
    public void findMySub(Context context) {
        DialogHelper.showProgressDialog(context, "数据加载中...");
        NewAPIManager.getInstance().getLogisticsAPI().goodsSubscriptionDetail(new HashMap<>()).enqueue(new ICallBack<BaseEntity<SubSetEntity>>() {
            @Override
            public void onSuccess(BaseEntity<SubSetEntity> data) {
                ldSub.postValue(data.getData());
            }
        });
//        APIManager.getInstance().getDriverAPI().findMySub(new HashMap<>()).enqueue(new ICallBack<BaseEntity<SubSetEntity>>() {
//            @Override
//            public void onSuccess(BaseEntity<SubSetEntity> data) {
//                ldSub.postValue(data.getData());
//            }
//
//            @Override
//            public void onFail() {
//                ldSub.postValue(new SubSetEntity());
//            }
//        });
    }

    /**
     * 获取车辆类型
     */
    public void getCarTypeList() {
        NewAPIManager.getInstance().getLogisticsAPI().getCarTypeAndLen("").enqueue(new ICallBack<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
            @Override
            public void onSuccess(BaseEntity<List<GoodsInfoTypeEntity3>> data) {
                ldCarType.postValue(data.getData());
            }
        });
    }


    //保存编辑 商机订阅设置
    public void saveSub(Context context, List<SubSetListEntity> list) {
        if (list == null || list.size() != 3) return;
        SubSetEntity entity = new SubSetEntity();
        entity.setCity(new ArrayList<>());
        entity.setDestCity(new ArrayList<>());
        entity.setCarType(new ArrayList<>());
        //
        List<CarriageSelectEntity> cityList = list.get(0).getList();
        List<CarriageSelectEntity> destCityList = list.get(1).getList();
        List<CarriageSelectEntity> typeList = list.get(2).getList();
        //
        adjustData(cityList, entity.getCity());
        adjustData(destCityList, entity.getDestCity());
        adjustData(typeList, entity.getCarType());
        //判断是否全空
        if (entity.getCity().isEmpty() && entity.getDestCity().isEmpty() && entity.getCarType().isEmpty()) {
            showTipDialog(context, entity);
        } else {
            realSave(context, entity);
        }
    }

    /**
     * 调整数据
     */
    private void adjustData(List<CarriageSelectEntity> list, List<CarriageSelectEntity> realList) {
        for (CarriageSelectEntity sub : list) {
            if (sub.getItemType() != SingleItemConstant.TYPE_TWO) {
                realList.add(sub);
            }
        }
    }

    /**
     * 空设置提示弹窗
     */
    private void showTipDialog(Context context, SubSetEntity entity) {
        new RoundDialog.Builder(context)
                .title("提示")
                .content("您当前未设置任何订阅项，确定要提交吗？")
                .confirmCallback(v -> realSave(context, entity))
                .show();
    }

    /**
     * 实际修改接口
     */
    public void realSave(Context context, SubSetEntity entity) {
        DialogHelper.showProgressDialog(context, "数据加载中...");
        APIManager.getInstance().getDriverAPI().saveSub(entity).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                boolean isFirst = MkvUtils.get().getMMKV().decodeBool(TAG_FIRST, true);
                if (isFirst) {
                    showFirstTipDialog(context);
                } else {
                    MToast.showToast(getApplication(), "操作成功");
                    ((Activity) context).finish();
                }
            }

            @Override
            public void onFail() {
                MToast.showToast(getApplication(), "操作成功");
            }
        });
    }

    /**
     * 第一次提示
     */
    private void showFirstTipDialog(Context context) {
        new RoundDialog.Builder(context)
                .title("设置成功")
                .content("一旦有新发布的货源时，我们将根据您的订阅项推送货源给您，您可在找货-订阅货源中快速查看")
                .confirm("我知道了")
                .singleBtn(true)
                .cancelable(false)
                .dismissListener(dialog -> {
                    //标识已经设置过了
                    MkvUtils.get().getMMKV().encode(TAG_FIRST, false);
                    ((Activity) context).finish();
                })
                .show();
    }

    /**
     * 检查重复城市
     */
    public boolean checkRepeatCity(List<CarriageSelectEntity> list, AddressEntity city) {
        if (list == null || list.size() == 0) {
            return false;
        }
        for (int i = 0; i < list.size(); i++) {
            CarriageSelectEntity entity = list.get(i);
            //防止选择重复城市
            if (!TextUtils.isEmpty(entity.getNo()) && entity.getNo().equals(city.getNo())) {
                MToast.showToast(getApplication(), "您已选择该城市，请选择其他城市");
                return true;
            }
        }
        return false;
    }

    /**
     * 检查重复车型
     */
    public boolean checkRepeatType(List<CarriageSelectEntity> list, GoodsInfoTypeEntity3 type) {
        if (list == null || list.size() == 0) {
            return false;
        }
        for (int i = 0; i < list.size(); i++) {
            CarriageSelectEntity entity = list.get(i);
            //防止选择重复城市
            if (!TextUtils.isEmpty(entity.getNo()) && entity.getNo().equals(type.getNo())) {
                MToast.showToast(getApplication(), "您已选择该车型，请选择其他车型");
                return true;
            }
        }
        return false;
    }
}
